package org.coderfun.fieldmeta.auth;

import org.coderfun.common.exception.AppException;
import org.coderfun.fieldmeta.common.EmailCaptchaService;
import org.coderfun.member.core.entity.Member;
import org.coderfun.member.core.exception.MemberErrorCode;
import org.coderfun.member.core.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class RegisterServiceImpl implements RegisterService {

	@Autowired
	MemberService memberService;
	
	@Autowired
	EmailCaptchaService captchaService;

	@Override
	public void register(String username, String email, String plainPassword, String captcha) {
		// TODO Auto-generated method stub
		if (!captchaService.valid(email, captcha)) {
			throw new AppException(MemberErrorCode.CAPTCHA_WORNG);
		} else if (memberService.checkUsernameExist(username)) {
			throw new AppException(MemberErrorCode.USER_NAME_EXIST);
		} else if (memberService.checkEmailExist(email)) {
			throw new AppException(MemberErrorCode.USER_EMAIL_EXIST);
		} else {
			Member member = new Member();
			member.setUsername(username);
			member.setEmail(email);
			member.setPlainPassword(plainPassword);
			memberService.save(member);
		}
	}

	@Override
	public void resetPassword(String email, String password, String captcha) {
		// TODO Auto-generated method stub
		if(!memberService.checkEmailExist(email)){
			throw new AppException(MemberErrorCode.USER_NOT_EXIST);
		}
		
		if (!captchaService.valid(email, captcha)) {
			throw new AppException(MemberErrorCode.CAPTCHA_WORNG);
		} 
		
		Member member = memberService.getByEmail(email);
		memberService.updatePassword(member.getId(), password);		
	}
}
